package br.com.felix.fwt.ui;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import br.com.felix.fwt.log.LoggerFactory;
import br.com.felix.fwt.ui.exception.ComponentRenderException;

/**
 * The Class ComboBox implements an HTML select component.
 * Each child you add will be a select option. So beware of the name and value properties of the
 * childs.
 */
public class ComboBox extends BaseComponent {

	private static final long serialVersionUID = 7518700585781614726L;

	private static Logger logger = LoggerFactory.getLogger(ComboBox.class);

	{
	    this.cssClass = "fwtcombobox";
	}
	
	
	/**
	 * Instantiates a new combo box.
	 */
	public ComboBox(){
	}
	

	/**
	 * Instantiates a new combo box and adds the informed options.
	 * */
	public ComboBox(List<Option> lstOptions) {
		this();
		add(lstOptions);
	}


	@Override
	public void add(BaseComponent ... children) {
		if(childs==null){
			childs = new ArrayList<BaseComponent>();
		}
		for(BaseComponent child:children)
			childs.add(child);
	}
	
	
	public void add(List<Option> lstOption) {
		if(childs==null){
			childs = new ArrayList<BaseComponent>();
		}
		childs.addAll(lstOption);
	}
	
	
	public void add(Option ...options) {
		if(childs==null){
			childs = new ArrayList<BaseComponent>();
		}
		for(Option option:options)childs.add(option);
	}


	/* (non-Javadoc)
	 * @see br.com.felix.fwt.ui.BaseComponent#write(java.io.PrintWriter)
	 */
	@Override
	public void write(PrintWriter out) throws ComponentRenderException {
		if(!authorized()) return;
		PresentationMode pMode = getPresentationMode();
		Option option;
		String myValue = getValue();
		switch(pMode){
			case EDIT:
				out.write("\n<select name=\"");
				out.write(getName());
				out.write("\" class=\"");
				out.write(cssClass);
				out.write("\" ");
				if(style!=null){
					out.write(style);
				}
				out.write(">");
				if(childs!=null){
					for(BaseComponent child:childs){
						option = (Option)child;
						if(child.getValue().equals(myValue)){
							option.selected = true;
						}
						else{
							option.selected = false;
						}
						child.write(out);
					}
				}
				out.write("\n</select>");
				break;
				
			case SHOW:
				if(childs!=null){
					for(BaseComponent child:childs){
						option = (Option)child;
						if(child.getValue().equals(myValue)){
							child.write(out);
							break;
						}
					}
				}
				break;
			case DELETED:
				if(childs!=null){
					for(BaseComponent child:childs){
						option = (Option)child;
						if(child.getValue().equals(myValue)){
							out.write("\n<del>");
							out.write(child.getName());
							out.write("</del>");
							break;
						}
					}
				}
				break;
		}
	}


	
    @Override
    public boolean isInputControl() {
        return true;
    }


}
